package com.aaa.marketresearch.dataresource.dao;

import com.aaa.marketresearch.dataresource.domain.Market;
import org.springframework.stereotype.Repository;

import javax.persistence.EntityManager;
import javax.persistence.NonUniqueResultException;
import javax.persistence.PersistenceContext;
import java.util.List;

/**
 * @author Nail
 */

@Repository
public class MarketDAOImpl implements MarketDAO {

    @PersistenceContext
    private EntityManager em;

    @Override
    public List<Market> getAll() {
        List<Market> result = em.createQuery("FROM Market m").getResultList();
        return result;
    }

    @Override
    public Market getById(Integer id) {
        final String query = "FROM Market m WHERE m.id=:id";

        try {
            Object obj = em.createQuery(query).setParameter("id", id).getSingleResult();
            return (Market)obj;
        } catch (NonUniqueResultException ex) {
            return null;
        }
    }

    @Override
    public void save(Market market) {
        this.em.merge(market);
    }

    @Override
    public boolean delete(Integer id) {
        final String query = "DELETE Market m WHERE m.id = :id";
        int count = em.createQuery(query).setParameter("id", id).executeUpdate();
        return (count > 0);
    }
}
